package com.station.model;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.google.gson.Gson;
import com.station.R;
import com.station.bean.BaseBean;
import com.station.bean.Tab1DataListBean;
import com.station.bean.Tab1DetailBean;
import com.station.bean.Tab2RefreshEvent;
import com.station.bean.YYSBean;
import com.station.databinding.ActivityTab1detailBinding;
import com.station.databinding.DialogXdBinding;
import com.station.databinding.XdlistBinding;
import com.station.http.MNetHttp;
import com.station.listener.HttpListener;
import com.station.listener.LoadStatusListener;
import com.station.listener.RxHttpListener;
import com.station.util.BindingUtil;
import com.station.util.GsonUtil;
import com.station.util.PreferencesUtil;
import com.station.util.Static;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by nbzl on 2017/10/18.
 */
public class Tab1DetailModel extends BaseModel {
    private boolean isEdit = false;
    private DialogXdBinding dialogview;
    private ActivityTab1detailBinding binding;
    private DatePickerDialog datePickerDialog;
    private FragmentManager manager;
    private LoadStatusListener loadstatus;
    public Map<String, String> params;
    private android.support.v7.app.AlertDialog.Builder addBuild;

    private String basictype = "", rate = "", linktype = "0", contractor="",contractor_name="",supplytype = "", compName = "", compId = "", channeltype = "", id = "";
    private List<Tab1DataListBean> channels;

    private Tab1DetailBean tab1bean = null;
    private List<YYSBean> yyslist = null;
    private List<YYSBean> cjdwlist=null;

    private boolean isSingle=true;


    public Tab1DetailModel(final Context context, FragmentManager manager, LoadStatusListener loadstatus) {
        super(context);
        this.loadstatus = loadstatus;
        this.manager = manager;
        params = new HashMap<String, String>();
        channels = new ArrayList<Tab1DataListBean>();
        yyslist=new ArrayList<YYSBean>();
        yyslist.add(new YYSBean("","请选择"));

        cjdwlist=new ArrayList<YYSBean>();
        cjdwlist.add(new YYSBean("","请选择"));

        Calendar calendar = Calendar.getInstance();
        datePickerDialog = DatePickerDialog.newInstance(new DataSelectListener(), calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);
        datePickerDialog.setYearRange(2000, 2028);
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.activity_tab1detail, null, false);

        binding.setClick(new ViewClick());
        binding.setData(null);
        binding.spinnerjztype.attachDataSource(app.getBaseTypeMap().get("value"));
        binding.spinnerxjtype.attachDataSource(app.getDatetypeMap().get("value"));
        binding.spinnerxdtype.attachDataSource(app.getJzxdtypeMap().get("value"));
        binding.spinnerlltype.attachDataSource(app.getLlutypeMap().get("value"));
        binding.spinnergdtype.attachDataSource(app.getGdtypeMap().get("value"));

        binding.spinnerxdtype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("Mytext", "--->" + app.getBaseTypeMap().get("key").get(position));
                channeltype = app.getJzxdtypeMap().get("key").get(position);
            }
        });

        binding.spinnerjztype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("Mytext", "--->" + app.getBaseTypeMap().get("key").get(position));
                basictype = app.getBaseTypeMap().get("key").get(position);
            }
        });
        binding.spinnerxjtype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.e("Mytext","--->"+app.getDatetypeMap().get("key").get(position));
                rate = app.getDatetypeMap().get("key").get(position);
            }
        });
        binding.spinnerlltype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.e("Mytext","--->"+app.getDatetypeMap().get("key").get(position));
                linktype = app.getLlutypeMap().get("key").get(position);
            }
        });
        binding.spinnergdtype.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.e("Mytext","--->"+app.getDatetypeMap().get("key").get(position));
                supplytype = app.getGdtypeMap().get("key").get(position);
            }
        });
        isEdit = ((Activity) context).getIntent().getBooleanExtra("isEdit", false);
        if (((Activity) context).getIntent().getStringExtra("id") != null) {
            postRequest();
            //isEdit=false;
        } else {
            loadstatus.hide(true, "");
            List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
            Map<String, Object> map2 = new HashMap<String, Object>();

            Map<String,String> p=new HashMap<String,String>();
            p.put("policecode",PreferencesUtil.getInstance(context).getLastLoginPoliceCode());

            map2.put("url", Static.LINKLIST);
            map2.put("param", p);
            datalist.add(map2);

            Map<String, Object> map3 = new HashMap<String, Object>();
            map3.put("url", Static.CJDWLIST);
            map3.put("param", p);
            datalist.add(map3);

            MNetHttp.getInstance().rxListRequest(datalist, new RequestListener());

            //loadstatus.show();
            //isEdit=true;
        }

        binding.setIsEdit(isEdit);


    }

    public void showAddDialog() {
        addBuild = new android.support.v7.app.AlertDialog.Builder(context);
        addBuild.setCancelable(false);
        addBuild.setTitle("提示");

        dialogview = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_xd, null, false);

        addBuild.setView(dialogview.getRoot());
        addBuild.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(dialogview.name.getText())) {
                    Static.showToast(context, "信道名称不能为空");
                } else if (TextUtils.isEmpty(dialogview.plv.getText())) {
                    Static.showToast(context, "无线频率不能为空");
                } else if (TextUtils.isEmpty(dialogview.plvh.getText())) {
                    Static.showToast(context, "频率号不能为空");
                } else {
                    Tab1DataListBean item = new Tab1DataListBean();
                    item.setChannelname(dialogview.name.getText().toString());
                    item.setChannelrate(dialogview.plv.getText().toString());
                    item.setRatenum(dialogview.plvh.getText().toString());
                    isSingle=!isSingle;
                    XdlistBinding xdlistBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.xdlist, null, false);
                    xdlistBinding.setItem(item);
                    xdlistBinding.setIsSingle(isSingle);
                    binding.xdlist.addView(xdlistBinding.getRoot());
                    channels.add(item);
                }

            }
        });
        addBuild.show();
    }

    public void postRequest() {
        //progressDialog.show();
        loadstatus.hide(true, "");

        params.put("id", ((Activity) context).getIntent().getStringExtra("id"));
        params.put("policecode",PreferencesUtil.getInstance(context).getLastLoginPoliceCode());
        //MNetHttp.getInstance().rxPostRequest(Static.TAB1DETAIL, params, Tab1DetailBean.class, new ListRequestListener());


        //MNetHttp.getInstance().rxPostRequest(Static.LINKLIST, new HashMap<String, String>(), YYSBean.class, new YYSListener());

        List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("url", Static.TAB1DETAIL);
        map1.put("param", params);

        datalist.add(map1);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("url", Static.LINKLIST);
        map2.put("param", params);
        datalist.add(map2);

        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("url", Static.CJDWLIST);
        map3.put("param", params);
        datalist.add(map3);

        MNetHttp.getInstance().rxListRequest(datalist, new RequestListener());
    }

    public ActivityTab1detailBinding getBinding() {
        return binding;
    }


    class RequestListener implements RxHttpListener {

        @Override
        public void finish() {

        }

        @Override
        public void fail(String msg) {

        }

        @Override
        public void next(Object obj) {
            if (((Activity) context).getIntent().getStringExtra("id") != null){
                if (tab1bean == null) {
                    tab1bean = GsonUtil.getInstance().getObject(obj.toString(), Tab1DetailBean.class);
                    if (tab1bean.getReturncode().equals("200")) {
                        binding.setData(tab1bean.getData());

                        binding.basictype.setText(app.getBasetypeItem().get(tab1bean.getData().getBasictype() == null ? "-1" : tab1bean.getData().getBasictype()));
                        binding.rate.setText(app.getDatetypeItem().get(tab1bean.getData().getRate() == null ? "0" : tab1bean.getData().getRate()));
                        binding.supplytype.setText(app.getGdtypeItem().get(tab1bean.getData().getSupplytype() == null ? "0" : tab1bean.getData().getSupplytype()));
                        binding.linktype.setText(app.getLlutypeItem().get(tab1bean.getData().getLinktype() == null ? "0" : tab1bean.getData().getLinktype()));
                        binding.channeltype.setText(app.getJzxdtypeItem().get(tab1bean.getData().getLinktype() == null ? "0" : tab1bean.getData().getLinktype()));


                        binding.spinnergdtype.setSelectedIndex(tab1bean.getData().getSupplytype() != null ? Integer.valueOf(tab1bean.getData().getSupplytype())+1 : 0);
                        binding.spinnerxjtype.setSelectedIndex(tab1bean.getData().getRate() != null ? Integer.valueOf(tab1bean.getData().getRate())+1 : 0);
                        binding.spinnerjztype.setSelectedIndex(tab1bean.getData().getBasictype() != null ? Integer.valueOf(tab1bean.getData().getBasictype()) + 1 : 0);
                        binding.spinnerxdtype.setSelectedIndex(tab1bean.getData().getChanneltype() != null ? Integer.valueOf(tab1bean.getData().getChanneltype())+1 : 0);
                        binding.spinnerlltype.setSelectedIndex(tab1bean.getData().getLinktype() != null ? Integer.valueOf(tab1bean.getData().getLinktype())+1 : 0);
                        for (int i = 0; i < tab1bean.getData().getList().size(); i++) {
                            XdlistBinding xdlistBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.xdlist, null, false);
                            xdlistBinding.setItem(tab1bean.getData().getList().get(i));
                            isSingle=!isSingle;
                            xdlistBinding.setIsSingle(isSingle);
                            binding.xdlist.addView(xdlistBinding.getRoot());
                        }

                        basictype = tab1bean.getData().getBasictype();
                        rate = tab1bean.getData().getRate();
                        linktype = tab1bean.getData().getLinktype();
                        supplytype = tab1bean.getData().getSupplytype();
                        channeltype = tab1bean.getData().getChanneltype();
                        channels.addAll(tab1bean.getData().getList());
                    }

                } else if (yyslist.size()==1) {
                    yyslist.addAll(GsonUtil.getInstance().getArray(obj.toString(), YYSBean[].class));
                    //yyslist.add(0,new YYSBean("","请选择"));
                    List<String> yyss = new ArrayList<String>();
                    for (YYSBean bean : yyslist) {
                        yyss.add(bean.getText());
                    }
                    compName = yyslist.get(0).getText();
                    compId = yyslist.get(0).getCode();
                    binding.spinneryystype.attachDataSource(yyss);
                    binding.spinneryystype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            compName = yyslist.get(position).getText();
                            compId = yyslist.get(position).getCode();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    //binding.spinneryystype.setSelectedIndex(tab1bean.getData());
                    loadstatus.show();
                }else if(cjdwlist.size()==1){
                    cjdwlist.addAll(GsonUtil.getInstance().getArray(obj.toString(), YYSBean[].class));
                    List<String> cj = new ArrayList<String>();
                    for (YYSBean bean : cjdwlist) {
                        cj.add(bean.getText());
                    }
                    if(tab1bean!=null){
                        contractor=tab1bean.getData().getContractor();
                        contractor_name=tab1bean.getData().getContractor_name();
                    }else{
                        contractor=cjdwlist.get(0).getCode();
                        contractor_name=cjdwlist.get(0).getText();
                    }
                    binding.spinnercontractor.attachDataSource(cj);
                    binding.spinnercontractor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            contractor = cjdwlist.get(position).getCode();
                            contractor_name = cjdwlist.get(position).getText();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    for(int i=0;i<cjdwlist.size();i++){
                        if(tab1bean!=null&&tab1bean.getData().getContractor().equals(cjdwlist.get(i).getCode())){
                            binding.spinnercontractor.setSelectedIndex(i);
                            break;
                        }
                    }

                }
            }else{
                if (yyslist.size()==1) {
                    yyslist.addAll(GsonUtil.getInstance().getArray(obj.toString(), YYSBean[].class));
                    //yyslist.add(0,new YYSBean("","请选择"));
                    List<String> yyss = new ArrayList<String>();
                    for (YYSBean bean : yyslist) {
                        yyss.add(bean.getText());
                    }
                    compName = yyslist.get(0).getText();
                    compId = yyslist.get(0).getCode();
                    binding.spinneryystype.attachDataSource(yyss);
                    binding.spinneryystype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            compName = yyslist.get(position).getText();
                            compId = yyslist.get(position).getCode();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    //binding.spinneryystype.setSelectedIndex(tab1bean.getData());
                    loadstatus.show();
                }else if(cjdwlist.size()==1){
                    cjdwlist.addAll(GsonUtil.getInstance().getArray(obj.toString(), YYSBean[].class));
                    List<String> cj = new ArrayList<String>();
                    for (YYSBean bean : cjdwlist) {
                        cj.add(bean.getText());
                    }
                    contractor=cjdwlist.get(0).getCode();
                    contractor_name=cjdwlist.get(0).getText();
                    binding.spinnercontractor.attachDataSource(cj);
                    binding.spinnercontractor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            contractor = cjdwlist.get(position).getCode();
                            contractor_name = cjdwlist.get(position).getText();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                }
            }


        }
    }

    /*class ListRequestListener implements HttpListener {

        @Override
        public void success(Object obj) {
            //progressDialog.dismiss();
            if (((Tab1DetailBean) obj).getReturncode().equals("200")) {
                binding.setData(((Tab1DetailBean) obj).getData());
                binding.spinnergdtype.setSelectedIndex(((Tab1DetailBean) obj).getData().getSupplytype() != null ? Integer.valueOf(((Tab1DetailBean) obj).getData().getSupplytype()) : 0);
                binding.spinnerxjtype.setSelectedIndex(((Tab1DetailBean) obj).getData().getRate() != null ? Integer.valueOf(((Tab1DetailBean) obj).getData().getRate()) : 0);
                binding.spinnerjztype.setSelectedIndex(((Tab1DetailBean) obj).getData().getBasictype() != null ? Integer.valueOf(((Tab1DetailBean) obj).getData().getBasictype()) + 1 : 0);
                binding.spinnerxdtype.setSelectedIndex(((Tab1DetailBean) obj).getData().getChanneltype() != null ? Integer.valueOf(((Tab1DetailBean) obj).getData().getChanneltype()) : 0);
                binding.spinnerlltype.setSelectedIndex(((Tab1DetailBean) obj).getData().getLinktype() != null ? Integer.valueOf(((Tab1DetailBean) obj).getData().getLinktype()) : 0);
                for (int i = 0; i < ((Tab1DetailBean) obj).getData().getList().size(); i++) {
                    XdlistBinding xdlistBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.xdlist, null, false);
                    xdlistBinding.setItem(((Tab1DetailBean) obj).getData().getList().get(i));
                    binding.xdlist.addView(xdlistBinding.getRoot());
                }

                id = ((Tab1DetailBean) obj).getData().getId();
                basictype = ((Tab1DetailBean) obj).getData().getBasictype();
                rate = ((Tab1DetailBean) obj).getData().getRate();
                linktype = ((Tab1DetailBean) obj).getData().getLinktype();
                supplytype = ((Tab1DetailBean) obj).getData().getSupplytype();
                channeltype = ((Tab1DetailBean) obj).getData().getChanneltype();
                channels.addAll(((Tab1DetailBean) obj).getData().getList());
            }
            loadstatus.show();
        }

        @Override
        public void fail(String msg) {
            loadstatus.hide(false, msg);
        }
    }*/


    class DataSelectListener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
            Log.e("Mytext", year + "-" + month + "-" + day);
            if (datePickerDialog.getTag().equals("createTime")) {
                binding.createTime.setText(year + "-" + (month + 1) + "-" + day);
            } else if (datePickerDialog.getTag().equals("endTime")) {
                binding.endTime.setText(year + "-" + (month + 1) + "-" + day);
            }
        }
    }

    public class ViewClick {
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.submit:
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("id", ((Activity) context).getIntent().getStringExtra("id")==null?"":((Activity) context).getIntent().getStringExtra("id"));
                    if(BindingUtil.isEmpty(binding.basicname).equals("")){
                        Static.showToast(context,"基站名称不能为空");
                        return;
                    }
                    if(BindingUtil.isEmpty(binding.addr).equals("")){
                        Static.showToast(context,"基站地址不能为空");
                        return;
                    }
                    if(BindingUtil.isEmpty(binding.longitude).equals("")){
                        Static.showToast(context,"基站经度不能为空");
                        return;
                    }
                    if(BindingUtil.isEmpty(binding.latitude).equals("")){
                        Static.showToast(context,"基站纬度不能为空");
                        return;
                    }
                    if(BindingUtil.isEmpty(binding.jwheight).equals("")){
                        Static.showToast(context,"机房高度不能为空");
                        return;
                    }
                    if(BindingUtil.isEmpty(binding.txheight).equals("")){
                        Static.showToast(context,"天线高度不能为空");
                        return;
                    }
                    if(basictype.equals("")||basictype.equals("-1")){
                        Static.showToast(context,"基站类型不能为空");
                        return;
                    }
                    if(channeltype.equals("")||channeltype.equals("-1")){
                        Static.showToast(context,"基站信道类型不能为空");
                        return;
                    }
                    params.put("basicname", BindingUtil.isEmpty(binding.basicname));
                    params.put("addr", BindingUtil.isEmpty(binding.addr));

                    params.put("longitude", BindingUtil.isEmpty(binding.longitude));
                    params.put("latitude", BindingUtil.isEmpty(binding.latitude));

                    params.put("jw_height", BindingUtil.isEmpty(binding.jwheight));
                    params.put("tx_height", BindingUtil.isEmpty(binding.txheight));
                    params.put("basictype", basictype);
                    params.put("rate", rate);
                    params.put("channelnum", BindingUtil.isEmpty(binding.channelnum));
                    params.put("linktype", linktype);
                    params.put("linkstripwidth", BindingUtil.isEmpty(binding.linkstripwidth));

                    params.put("linkid", BindingUtil.isEmpty(binding.linkid));
                    params.put("cost", BindingUtil.isEmpty(binding.cost));
                    params.put("supplytype", supplytype);
                    params.put("voltage", BindingUtil.isEmpty(binding.voltage));

                    params.put("gbtime", BindingUtil.isEmpty(binding.endTime));
                    params.put("createdate", BindingUtil.isEmpty(binding.createTime));
                    //params.put("subordinatesystem", BindingUtil.isEmpty(binding.subordinatesystem));
                    params.put("contractor",contractor);//
                    params.put("contractor_name",contractor_name);//
                    params.put("maintenanceunit", BindingUtil.isEmpty(binding.maintenanceunit));
                    params.put("telephone", BindingUtil.isEmpty(binding.telephone));

                    params.put("channeltype", channeltype);

                    for (int i = 0; i < channels.size(); i++) {
                        params.put("list[" + i + "].channelname", channels.get(i).getChannelname());
                        params.put("list[" + i + "].channelrate", channels.get(i).getChannelrate());
                        params.put("list[" + i + "].ratenum", channels.get(i).getRatenum());
                        params.put("list[" + i + "].channelsort", i + "");
                    }

                    params.put("compName", compName.equals("请选择")?"":compName);
                    params.put("compId", compId);
                    params.put("policecode", PreferencesUtil.getInstance(context).getLastLoginPoliceCode());
                    Gson gson = new Gson();
                    String str = gson.toJson(params);
                    Log.e("Mytext", "-->" + str);
                    MNetHttp.getInstance().rxPostRequest(Static.INPUTTAB1, params, BaseBean.class, new UpDataListener());

                    //params.put("deptcode",""


                    break;
                case R.id.addXd:
                    //addBuild.show();
                    showAddDialog();
                    break;
                case R.id.createTime:
                    if (isEdit) {
                        datePickerDialog.show(manager, "createTime");
                    }

                    break;
                case R.id.endTime:
                    if (isEdit) {
                        datePickerDialog.show(manager, "endTime");
                    }
                    break;
                case R.id.createImg:
                    if (isEdit) {
                        datePickerDialog.show(manager, "createTime");
                    }

                    break;
                case R.id.endImg:
                    if (isEdit) {
                        datePickerDialog.show(manager, "endTime");
                    }
                    break;
            }
        }
    }

    class UpDataListener implements HttpListener {

        @Override
        public void success(Object obj) {
            if (((BaseBean) obj).getReturncode().equals("200")) {
                 Static.showToast(context,"操作成功");
                Tab2RefreshEvent event = new Tab2RefreshEvent(true);
                EventBus.getDefault().post(event);
                ((Activity)context).finish();
            }else{
                Static.showToast(context,"操作失败，请重试");
            }
        }

        @Override
        public void fail(String msg) {
            Static.showToast(context,msg);
        }
    }

}
